package tyk.utils;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.data.time.*;
import org.jfree.data.xy.XYSeries;
import tyk.Dao.BaseDao;
import tyk.pojo.Visit;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class  CreateBufferedImage{
    public static void main() throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        List<Visit> data = getDataFromDatabase();

        TimeSeries series = new TimeSeries("Only__Book");
        RegularTimePeriod period = new Minute(new Date());
        for (int i = 6; i >=0; --i) {
            series.add(new Minute(data.get(i).getTime()), data.get(i).getCount());
            //period = period.next();
        }

        TimeSeriesCollection dataset = new TimeSeriesCollection(series);

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
                "近一周网站流量统计图",
                "日期",
                "人数",
                dataset,
                true,
                true,
                false
        );

        // 设置背景色为白色
        chart.setBackgroundPaint(java.awt.Color.WHITE);

        // 设置标题字体
        Font titleFont = new Font("宋体", Font.BOLD, 18);
        chart.getTitle().setFont(titleFont);

        // 设置横轴标签字体
        Font domainLabelFont = new Font("宋体", Font.PLAIN, 14);
        chart.getXYPlot().getDomainAxis().setLabelFont(domainLabelFont);

        // 设置纵轴标签字体
        Font rangeLabelFont = new Font("宋体", Font.PLAIN, 14);
        chart.getXYPlot().getRangeAxis().setLabelFont(rangeLabelFont);

        // 设置横轴的时间格式
        DateAxis domainAxis = (DateAxis) chart.getXYPlot().getDomainAxis();
        domainAxis.setDateFormatOverride(new SimpleDateFormat("MM-dd"));
        String projectPath = System.getProperty("user.dir"); // 获取当前工程路径
        // 保存图表为 JPG 图片
        File outputFile = new File("./web/Images/Websitetrafficstatisticstable.jpg"); // 存储在当前工程的 web/uploads 文件夹下
        //File outputFile = new File("Websitetrafficstatisticstable.jpg");
        try {
            ImageIO.write(chart.createBufferedImage(500, 300), "jpg", outputFile);
        } catch (IOException e) {
            System.out.println("保存 JPG 文件失败：" + e.getMessage());
        }
    }


    private static List<Visit> getDataFromDatabase() throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        // 连接数据库，查询最近一周的人流量数据
        // 返回 List<Integer> 类型的数据
        List<Visit> data = new ArrayList<>();
        BaseDao baseDao=new BaseDao();
        String sql="select time,count from visit order by id desc limit 7";
        data=baseDao.executeQuery(Visit.class,sql);
        return data;
    }
}
